package com.alan.camunda.boot.util;

import org.camunda.bpm.engine.impl.el.Expression;
import org.camunda.bpm.engine.impl.el.ExpressionManager;

import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class CacheableExpressionManager {

    private final ExpressionManager innerManager;

    private final ConcurrentHashMap<String, Expression> cachedExpressions = new ConcurrentHashMap<>();

    public CacheableExpressionManager(ExpressionManager innerManager) {
        // 之后可以考虑注册自己的 Function
        this.innerManager = innerManager;

        try {
            Method m7 = CacheableExpressionManager.class.getDeclaredMethod("UPPER", String.class);
            Method m1 = CacheableExpressionManager.class.getDeclaredMethod("uuid");
            Method m2 = CacheableExpressionManager.class.getDeclaredMethod("And", boolean.class, boolean.class);
            Method m3 = CacheableExpressionManager.class.getDeclaredMethod("ToInt", String.class);
            innerManager.addFunction("uuid", m1);
            innerManager.addFunction("And", m2);
            innerManager.addFunction("ToInt", m3);
            innerManager.addFunction("UPPER", m7);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 根据表达式字符串获得一个表达式对象，多次调用相同的表达式会返回同一个对象
     * @param expression
     * @return
     */
    public Expression getExpression(String expression) {
        return cachedExpressions.computeIfAbsent(expression, innerManager::createExpression);
    }

    /**
     * 生成一个 UUID 的自定义方法
     * @return
     */
    public static String uuid() {
        return UUID.randomUUID().toString().toUpperCase();
    }

    public static String UPPER(String str) {
        return str.toUpperCase();
    }

    public static boolean And(boolean a, boolean b) {
        return a && b;
    }

    public static int ToInt(String s) {
        return Integer.parseInt(s);
    }

}
